<template>
  <!-- el-upload
         action:必传参数 ，它是用于配制上传接口地址
         name:上传文件对应的字段名，默认值：file
         show-file-list:是否显示上传文件列表
         on-success:上传成功的回调：可以拿到上传成功后的接口返回值，上传的文件对象，它有二个参数(res:接口返回值,file:{raw:上传的文件对象})
         before-upload:上传前的限制，常用于限制上传文件的大小与类型
         http-request:类似于van-uploader组件内的after-read,它是用于自定义上传
         van-uploader
             before-read
             after-read

       腾讯云上传
            1:下载插件cos-js-sdk-v5
            2:导入与实例化
            3：
                cos.putObject(
                    {
                    Bucket: 'abc-1305249343', // 存储桶名字
                    Region: 'ap-chongqing' ,  // 服务器地域标识
                    Key: file.name ,  // 上传的文件名，一定要字符串
                    StorageClass: 'STANDARD',  // 固定参数
                    Body: file,   // 上传的文件对象
                    onProgress: function(progressData) {
                        // 上传的进度条值
                        console.log(JSON.stringify(progressData))
                    }
                    },
                    function(err, data) {
                    // err:如果出错显示错误信息   data:正常返回上传成功的文件地址
                    console.log(err || data)
                    }
                )
      图片的回显：
        父传子上传组件一张图片地址，子组件显示出来
        基本的父传子
           v-model
               子组件标签   :value="父组件属性"   @input="父组件属性=$event"
               子组件标签   v-model="父组件属性"

               子组件内
                  props:['value'],
                  model:{
                    prop:'value',
                    event:'input'
                  }
                  this.$emit('input',实参值)

        图片的删除
            1：布局html有删除图标
               默认不显示，鼠标移入相应区域才显示
            2：点击删除清空value的值
                 通过input事件实现修改清空value的值

        图片的预览
           1：布局
                鼠标移入icon
                弹框dialog
           2:点击icon显示dialog

     -->

  <div class="upload-img">
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="httpRequest"
    >
      <img v-if="value" v-errorImg :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <div v-if="value" class="del el-icon-circle-close" @click="del" />
    <div v-if="value" class="show el-icon-zoom-in" @click="showBig = true" />
    <transition name="progress">
      <el-progress
        v-if="show"
        class="progress"
        type="circle"
        :percentage="percentage"
        :width="178"
      />
    </transition>
    <el-dialog title="预览" :visible.sync="showBig">
      <div style="text-align: center">
        <img v-errorImg class="img-big" :src="value" alt="">
      </div>
    </el-dialog>
  </div>
</template>
<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDNXR8bpeSF1JL8EyZopxRfdHgqGUeuEn8', // 身份识别 ID
  SecretKey: 'HJ9mAbQEn7jgjY9swEI6yAamk7MN8hty' // 身份密钥
})
export default {
  name: 'UploadImg',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      //   imageUrl: ''
      showBig: false,
      show: false,
      percentage: 0
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG,PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    httpRequest(res) {
      console.log(res.file)
      //   const that = this
      this.show = true
      cos.putObject(
        {
          Bucket: 'abc-1305249343' /* 必须 存储桶*/,
          Region: 'ap-chongqing' /* 存储桶所在地域，必须字段 */,
          Key: res.file.name /* 必须 */,
          StorageClass: 'STANDARD',
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            // 上传进度
            // console.log(JSON.stringify(progressData))
            this.percentage = +(progressData.percent * 100).toFixed(2)
            if (progressData.percent === 1) {
              setTimeout(() => {
                this.show = false
              }, 1000)
            }
          }
        },
        (err, data) => {
          console.log(err || data)
          this.$emit('input', 'http://' + data.Location)
          //   this.imageUrl = 'http://' + data.Location
        }
      )
    },
    // 删除事件
    del() {
      this.$emit('input', '')
    }
  }
}
</script>
<style lang="scss" scoped>
// scoped:只管当前组件与子组件的最外层
.avatar-uploader ::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader ::v-deep .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.upload-img {
  position: relative;
  width: 178px;
  &:hover {
    .del {
      display: block;
    }
    .show {
      display: block;
    }
  }
  .del,
  .show {
    position: absolute;
    top: 0;
    right: 0;
    font-size: 30px;
    color: #f00;
    cursor: pointer;
    display: none;
    &:hover {
      color: goldenrod;
    }
  }
  .show {
    right: 50px;
  }
  .img-big {
    width: 80%;
  }
  .progress {
    position: absolute;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.4);
    ::v-deep .el-progress__text {
      color: #fff;
    }
  }
  .progress-enter,
  .progress-leave-to {
    opacity: 0;
  }
  .progress-enter-active,
  .progress-leave-active {
    transition: all 0.5s;
  }
}
</style>
